package com.example.baimao_tp.ui.screen

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.baimao_tp.R
import com.example.baimao_tp.viewmodel.GuideHighlightArea
import com.example.baimao_tp.viewmodel.CameraViewModel

/**
 * 引导界面覆盖层组件
 */
@Composable
fun GuideOverlay(
    viewModel: CameraViewModel,
    onGuideComplete: () -> Unit = {}
) {
    val currentStep = viewModel.currentGuideStep
    val highlightArea = viewModel.getCurrentGuideHighlightArea()
    val context = LocalContext.current
    val configuration = LocalConfiguration.current

    // 手指动画状态
    val fingerAnimation = rememberInfiniteTransition(label = "finger_animation")
    val fingerOffset by fingerAnimation.animateFloat(
        initialValue = 0f,
        targetValue = 20f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = EaseInOutCubic),
            repeatMode = RepeatMode.Reverse
        ), label = "finger_offset"
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xCC000000)) // 半透明黑色背景
            .clickable {
                // 点击外部区域进入下一步
                if (currentStep == 2) {
                    viewModel.completeGuide(context)
                    onGuideComplete()
                } else {
                    viewModel.nextGuideStep()
                }
            }
    ) {
        // 高亮区域背景
        HighlightArea(
            highlightArea = highlightArea,
            modifier = Modifier.fillMaxSize()
        )

        // 引导内容卡片
        GuideContentCard(
            currentStep = currentStep,
            highlightArea = highlightArea,
            fingerOffset = fingerOffset,
            onNext = {
                if (currentStep == 2) {
                    viewModel.completeGuide(context)
                    onGuideComplete()
                } else {
                    viewModel.nextGuideStep()
                }
            },
            onSkip = {
                viewModel.skipGuide(context)
                onGuideComplete()
            },
            modifier = Modifier.fillMaxSize()
        )
    }
}

/**
 * 高亮区域组件
 */
@Composable
private fun HighlightArea(
    highlightArea: GuideHighlightArea,
    modifier: Modifier = Modifier
) {
    Box(modifier = modifier) {
        when (highlightArea) {
            GuideHighlightArea.REFERENCE_THUMBNAIL -> {
                // 左下角高亮区域
                Box(
                    modifier = Modifier
                        .align(Alignment.BottomStart)
                        .padding(start = 16.dp, bottom = 130.dp)
                        .size(width = 70.dp, height = 90.dp)
                        .background(
                            Color(0xFF0099FF),
                            RoundedCornerShape(8.dp)
                        )
                )
            }
            GuideHighlightArea.EXPANDED_IMAGE -> {
                // 中央高亮区域
                Box(
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(width = 360.dp, height = 400.dp)
                        .background(
                            Color(0xFF0099FF),
                            RoundedCornerShape(12.dp)
                        )
                )
            }
            GuideHighlightArea.SETTINGS_BUTTON -> {
                // 右上角高亮区域
                Box(
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .padding(end = 16.dp, top = 32.dp)
                        .size(40.dp)
                        .background(
                            Color(0xFF0099FF),
                            RoundedCornerShape(20.dp)
                        )
                )
            }
        }
    }
}

/**
 * 引导内容卡片组件
 */
@Composable
private fun GuideContentCard(
    currentStep: Int,
    highlightArea: GuideHighlightArea,
    fingerOffset: Float,
    onNext: () -> Unit,
    onSkip: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 计算卡片位置，避免遮挡高亮区域
    val cardPosition = when (highlightArea) {
        GuideHighlightArea.REFERENCE_THUMBNAIL -> {
            // 参考图片在左下角，卡片显示在上方
            Alignment.TopCenter
        }
        GuideHighlightArea.EXPANDED_IMAGE -> {
            // 图片在中央，卡片显示在下方
            Alignment.BottomCenter
        }
        GuideHighlightArea.SETTINGS_BUTTON -> {
            // 设置按钮在右上角，卡片显示在左侧或下方
            Alignment.Center
        }
    }

    Box(
        modifier = modifier,
        contentAlignment = cardPosition
    ) {
        Card(
            modifier = Modifier
                .padding(16.dp)
                .width(280.dp),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color.White
            ),
            elevation = CardDefaults.cardElevation(
                defaultElevation = 8.dp
            )
        ) {
            Column(
                modifier = Modifier
                    .padding(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 标题
                Text(
                    text = stringResource(
                        when (currentStep) {
                            0 -> R.string.guide_title_1
                            1 -> R.string.guide_title_2
                            2 -> R.string.guide_title_3
                            else -> R.string.guide_title_1
                        }
                    ),
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                // 描述
                Text(
                    text = stringResource(
                        when (currentStep) {
                            0 -> R.string.guide_desc_1
                            1 -> R.string.guide_desc_2
                            2 -> R.string.guide_desc_3
                            else -> R.string.guide_desc_1
                        }
                    ),
                    fontSize = 14.sp,
                    color = Color.Gray,
                    textAlign = TextAlign.Center,
                    lineHeight = 20.sp,
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 手势指示（根据步骤显示不同的指示）
                GestureIndicator(
                    currentStep = currentStep,
                    fingerOffset = fingerOffset,
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 按钮区域
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 跳过按钮
                    TextButton(
                        onClick = onSkip,
                        modifier = Modifier
                    ) {
                        Text(
                            text = stringResource(R.string.guide_skip),
                            color = Color.Gray,
                            fontSize = 14.sp
                        )
                    }

                    // 下一步/完成按钮
                    Button(
                        onClick = onNext,
                        modifier = Modifier,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF0099FF)
                        )
                    ) {
                        Text(
                            text = stringResource(
                                if (currentStep == 2) R.string.guide_got_it else R.string.guide_next
                            ),
                            color = Color.White,
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
            }
        }
    }

    // 手指动画覆盖层（在第二步显示）
    if (currentStep == 1 && highlightArea == GuideHighlightArea.EXPANDED_IMAGE) {
        SwipeFingerAnimation(
            fingerOffset = fingerOffset,
            modifier = Modifier.fillMaxSize()
        )
    }
}

/**
 * 手势指示器组件
 */
@Composable
private fun GestureIndicator(
    currentStep: Int,
    fingerOffset: Float,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier.size(60.dp),
        contentAlignment = Alignment.Center
    ) {
        when (currentStep) {
            0 -> {
                // 点击手势指示
                Text(
                    text = "👆",
                    fontSize = 32.sp,
                    modifier = Modifier.offset(y = (-fingerOffset).dp)
                )
            }
            1 -> {
                // 滑动手势指示
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "👉",
                        fontSize = 24.sp,
                        modifier = Modifier.offset(x = (-fingerOffset).dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("👈", fontSize = 24.sp)
                }
            }
            2 -> {
                // 点击设置手势指示
                Text(
                    text = "👆",
                    fontSize = 32.sp,
                    modifier = Modifier.offset(y = (-fingerOffset).dp)
                )
            }
        }
    }
}

/**
 * 滑动手指动画组件
 */
@Composable
private fun SwipeFingerAnimation(
    fingerOffset: Float,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier.fillMaxSize()
    ) {
        // 左滑手指
        Text(
            text = "👉",
            fontSize = 40.sp,
            modifier = Modifier
                .align(Alignment.Center)
                .offset(x = (-180).dp + fingerOffset.dp)
        )

        // 右滑手指
        Text(
            text = "👈",
            fontSize = 40.sp,
            modifier = Modifier
                .align(Alignment.Center)
                .offset(x = 180.dp - fingerOffset.dp)
        )
    }
}